﻿// /****************************************************************************************************************************
//  * 项目名称： 
//  * 类 名 称：CarPainticRushOrderService
//  * 功能说明：
//  * 版    本：0.0.1
//  * 作    者：史垚祎
//  * 邮    箱：396038130@qq.com
//  * 创建时间：2024/10/17 15:57
//  * 更新人：
//  * 更新时间：
//  * 更新说明：
// /****************************************************************************************************************************/
//
using System;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Licai;
using NP.BPMReportPlatform.Licai.Dto;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using NP.BPMReportPlatform.Car.Dto;
using System.Linq;
using System.Net.NetworkInformation;
using System.Diagnostics;
using NP.BPMReportPlatform.Entities.BPM_Engine;

namespace NP.BPMReportPlatform.Car
{
    public class CarPainticRushOrderService : BPMReportPlatformAppService, ICarPainticRushOrderService
    {
        readonly SqlSugarClient _db;
        readonly SqlSugarClient _dbPlatform;
        readonly SqlSugarClient _engine;
        readonly IBPMUtilsAppService _bPMUtilsApp;
        readonly IBPMPlatformAppService _iBPMPlatformApp;
        public CarPainticRushOrderService(ISqlSugarAppService sqlSugarAppService,
            IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _engine = sqlSugarAppService.GetEngineInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CarPainticRushOrderOutPut>> GetAllAsync(GetCarPainticRushOrderInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceId, userId));
            InitField(listViewDto);
            return new PagedResultDto<CarPainticRushOrderOutPut>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<CarPainticRushOrderOutPut>> ExportAsync(GetCarPainticRushOrderInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            InitField(listViewDto);
            return listViewDto;
        }

        void InitField(List<CarPainticRushOrderOutPut> list)
        {
            if (list != null && list.Any())
            {
                var ApplyReasonList = _db.Queryable<KeyValues>().Where(x => x.CatalogCode == "CarPainticRushOrderApplyReason").ToList();

                var SickCountList = _db.Queryable<KeyValues>().Where(x => x.CatalogCode == "CarPainticRushOrderSickCount").ToList();
                var noList = list.Select(x => x.InstanceId).ToList();
                //获取审批人
                var aList = _engine.Queryable<Activities>().Where(x => noList.Contains(x.InstanceNumber) && x.GrandNodeType == "normal")
                    .InnerJoin(_engine.Queryable<ActivityResolvers>(), (a, b) => a.ActivityId == b.ActivityId)
                    .Select((a, b) => new
                    {
                        a.ActivityId,
                        a.InstanceNumber,
                        a.Name,
                        a.Order,
                        a.Status,
                        a.FinishTime,
                        AName = b.Name,
                        b.Type
                    }).ToList();

                var atyList = aList.Where(x => x.Type != 0).Select(x => x.ActivityId.ToString()).ToList();

                var tList = new List<Tasks>();
                if (atyList.Any())
                {
                    tList = _engine.Queryable<Tasks>().Where(x => atyList.Contains(x.ActivityId)).ToList();
                }
                list.ForEach(item =>
                {
                    string name = "";
                    switch (item.Status)
                    {
                        case -1:
                            name = "未通过";
                            break;
                        case 0:
                            name = "待审核";
                            break;
                        case 1:
                            name = "已通过";
                            break;
                        default:
                            name = "-";
                            break;
                    }
                    item.StatusName = name;

                    item.ApplyReason = ApplyReasonList.FirstOrDefault(x => x.Code == item.ApplyReason)?.Name ?? "";
                    item.SickCount = SickCountList.FirstOrDefault(x => x.Code == item.SickCount)?.Name ?? "";

                    var apList = aList.Where(x => x.InstanceNumber == item.InstanceId).OrderBy(x => x.Order).ToList();

                    if (apList.Any())
                    {
                        item.CurrentOperationUserName = apList.LastOrDefault()?.AName ?? "";

                        item.Node1Name = apList.FirstOrDefault()?.Name ?? "";
                        item.Node1Approve = apList.FirstOrDefault()?.AName ?? "";
                        if (apList.FirstOrDefault().Status != 1)
                        {
                            item.Node1ApproveTime = apList.FirstOrDefault()?.FinishTime;
                        }

                        if (apList.FirstOrDefault().Type != 0)
                        {
                            var aid = apList.FirstOrDefault().ActivityId.ToString();
                            item.Node1Name = string.Join(',', tList.Where(x => x.ActivityId == aid).Select(x => x.UserName));

                            item.CurrentOperationUserName = item.Node1Approve;
                        }


                        if (apList.Count >= 2)
                        {
                            item.Node2Name = apList[1].Name;
                            item.Node2Approve = apList[1].AName;
                            if (apList[1].Status != 1)
                            {
                                item.Node2ApproveTime = apList[1].FinishTime;
                            }

                            if (apList[1].Type != 0)
                            {
                                var aid = apList[1].ActivityId.ToString();
                                item.Node2Approve = string.Join(',', tList.Where(x => x.ActivityId == aid).Select(x => x.UserName));

                                item.CurrentOperationUserName = item.Node2Approve;
                            }
                        }

                        if (apList.Count >= 3)
                        {
                            item.Node3Name = apList[2].Name;
                            item.Node3Approve = apList[2].AName;
                            if (apList[2].Status != 1)
                            {
                                item.Node3ApproveTime = apList[2].FinishTime;
                            }

                            if (apList[2].Type != 0)
                            {
                                var aid = apList[2].ActivityId.ToString();
                                item.Node3Approve = string.Join(',', tList.Where(x => x.ActivityId == aid).Select(x => x.UserName));

                                item.CurrentOperationUserName = item.Node3Approve;
                            }
                        }

                        if (apList.Count >= 4)
                        {
                            item.Node4Name = apList[3].Name;
                            item.Node4Approve = apList[3].AName;
                            if (apList[3].Status != 1)
                            {
                                item.Node4ApproveTime = apList[3].FinishTime;
                            }

                            if (apList[3].Type != 0)
                            {
                                var aid = apList[3].ActivityId.ToString();
                                item.Node3Approve = string.Join(',', tList.Where(x => x.ActivityId == aid).Select(x => x.UserName));

                                item.CurrentOperationUserName = item.Node4Approve;
                            }
                        }
                    }



                });
            }
        }

        private ISugarQueryable<CarPainticRushOrderOutPut> GetQueryable(GetCarPainticRushOrderInput input)
        {
            #region 发起时间
            var SubmitDateEnd = DateTime.Now;
            var SubmitDateStrat = DateTime.Now;
            if (input.ApplyStartDate.HasValue)
            {
                SubmitDateStrat = input.ApplyStartDate.Value;
            }
            if (input.ApplyEndDate.HasValue)
            {
                SubmitDateEnd = input.ApplyEndDate.Value.AddDays(1);
            }
            #endregion

            var noList = new List<string>();
            if (!string.IsNullOrEmpty(input.InstanceId))
            {
                noList = input.InstanceId.Split(new char[] { ',', ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }


            var uQuery = _dbPlatform.Queryable<Users>()
                .AS("BPM_Platform.Users");
            var pQuery = _db.Queryable<BusinessProcessesNew>()
                .WhereIF(input.ApplyStartDate.HasValue, x => x.StartTime >= SubmitDateStrat)
                .WhereIF(input.ApplyEndDate.HasValue, x => x.StartTime < SubmitDateEnd);

            var nStatus = input.Status.HasValue ? input.Status.Value : 0;

            var tQuery = _db.Queryable<CarPainticRushOrder>()
                .WhereIF(!string.IsNullOrEmpty(input.InstanceId), x => noList.Contains(x.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.MaterialName), x => x.MaterialName.Contains(input.MaterialName))
                .WhereIF(!string.IsNullOrEmpty(input.ProductionLine), x => x.ProductionLine.Equals(input.ProductionLine))
                .WhereIF(!string.IsNullOrEmpty(input.Factory), x => x.Factory == input.Factory)

                .WhereIF(input.Status.HasValue, x => x.CPStatus == nStatus);


            var query = tQuery.InnerJoin(pQuery, (t, p) => p.InstanceId == t.InstanceNumber)
                    .InnerJoin(uQuery, (t, p, u) => p.StartUserId == u.UserId)
                    .OrderBy((t, p, u) => p.StartTime, OrderByType.Desc)
                    .Select((t, p, u) => new CarPainticRushOrderOutPut()
                    {
                        InstanceId = p.InstanceId,
                        CreateDate = p.StartTime,
                        StartUserName = p.StartUserName,
                        ApplyReason = t.ApplyReason,
                        ArriveTime = t.ArriveTime,
                        Checked1 = t.Checked1,
                        Checked2 = t.Checked2,
                        Checked3 = t.Checked3,
                        Checked4 = t.Checked4,
                        Contacts = t.Contacts,
                        CustomerName = t.CustomerName,
                        Factory = t.Factory,
                        FinishTime = t.FinishTime,
                        FormulaType = t.FormulaType,
                        Grade = t.Grade,
                        Industry = t.Industry,
                        MaterialCode = t.MaterialCode,
                        MaterialName = t.MaterialName,
                        NewNo = t.NewNo,
                        OrderCount = t.OrderCount,
                        ProductionLine = t.ProductionLine,
                        Remark = t.Remark,
                        Remark1 = t.Remark1,
                        Remark2 = t.Remark2,
                        Remark3 = t.Remark3,
                        Remark4 = t.Remark4,
                        SickCount = t.SickCount,
                        Status = t.CPStatus
                    });
            return query;
        }

    }
}

